﻿#include "mygraphicsview.h"
#include <QBuffer>
#include <QDebug>
#include <QDir>
#include <QJsonArray>
#include <QJsonDocument>
#include <QJsonObject>
#include <QLabel>
#include <qdatetime.h>
#include <qmessagebox.h>

#include "TmItem/tm_pointlineitem.h"

#include "TmItem/tm_rectitem.h"
#define SCALE_MAX       50
#define ZOOMUP_VALUE    1.1
#define ZOOMDOWN_VALUE  0.9

MyGraphicsView::MyGraphicsView(QWidget *parent) : QGraphicsView(parent)
{
    g_curScaleValue = 1;
    m_scene = new QGraphicsScene(this);
    this->setScene(m_scene);
    this->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);//隐藏水平条
    this->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);//隐藏竖
    this->setTransformationAnchor(QGraphicsView::AnchorUnderMouse);//缩放时，鼠标指针悬停在视图的某个点保持在鼠标指针下方
    this->setResizeAnchor(QGraphicsView::AnchorUnderMouse);//视图窗口大小发生变化时保持鼠标下面的图形项位置不变

    m_PixmapItem = new QGraphicsPixmapItem();

    qDebug()<<"g_RobotChassisLength="<<g_RobotChassisLength<<g_RobotChassisWidth<<g_RobotChassisRadius<<g_map_resolution;
    m_RobotItem = new TM_RobotItem(g_RobotChassisLength/(g_map_resolution*100),g_RobotChassisWidth/(g_map_resolution*100),g_RobotChassisRadius/(g_map_resolution*100));//x,y 为左上角的图元局部坐标，图元中心点为0,0
    m_RobotItem->setData(ItemId,"RobotView");
    m_scene->addItem(m_RobotItem);
    m_RobotItem->setVisible(false);

    m_newMapEdit = new MapEdit();
    connect(this,&MyGraphicsView::sig_MapEditPixmap,m_newMapEdit,&MapEdit::slot_MapPixmap,Qt::QueuedConnection);
    connect(this,&MyGraphicsView::sig_MapEditData,m_newMapEdit,&MapEdit::slot_newMapEdit,Qt::QueuedConnection);
    connect(m_newMapEdit,&MapEdit::sig_EndMapPixmap,this,&MyGraphicsView::slot_mapPixmap,Qt::QueuedConnection);
    m_newMapEdit->moveToThread(&m_MapEditThread);
    m_MapEditThread.start();

    m_EraserItem = new QGraphicsRectItem(-5,-5,10,10);
    m_EraserItem->setFlag(QGraphicsItem::ItemIsMovable,false);
    m_EraserItem->setBrush(QBrush(Qt::red));
    m_EraserItem->setPen(QPen(Qt::red,1));

}

MyGraphicsView::~MyGraphicsView()
{
    m_MapEditThread.quit();
    m_MapEditThread.wait();
    if(m_newMapEdit)
    {
        m_newMapEdit->deleteLater();
        m_newMapEdit = nullptr;
    }
    delete m_PixmapItem;
    delete m_RobotItem;
}

void MyGraphicsView::on_LoadMapfilePath(QString Path)
{
    if(m_scene->items().contains(m_RobotItem))
        m_scene->removeItem(m_RobotItem);
    delete m_RobotItem;
    QDir dir(Path);
    QStringList filesList = dir.entryList(QDir::Files);
    for(int i=0;i<filesList.length();i++)
    {
        if(QString(filesList[i]).endsWith(".yaml"))
        {
            on_setMapYaml(Path+"/"+QString(filesList[i]));
            break;
        }
    }
    for(int i=0;i<filesList.length();i++)
    {
        if(QString(filesList[i]).endsWith(".pgm"))
        {
            QString PixmapPath = Path+"/"+QString(filesList[i]);
            QPixmap image;
            image.load(PixmapPath);
            //image = image.convertToFormat(QImage::Format_Grayscale8);
            on_setPixmap(image,QString(filesList[i]).left(QString(filesList[i]).indexOf(".")));
            break;
        }
    }
    for(int i=0;i<filesList.length();i++)
    {
        if(QString(filesList[i]).endsWith(g_CurrentMapID+".json"))
        {
            on_setPointLine(Path+"/"+QString(filesList[i]));
            break;
        }
    }

    if(!g_is_OpenMapEdit)
    {
        m_bezileItemList.clear();
        QList<QGraphicsItem*>itemList = m_scene->items();
        foreach(QGraphicsItem  *item,itemList)
        {
            if(item->data(ItemDesciption).toString() == ItemBezier_Strat
                || item->data(ItemDesciption).toString() == ItemBezier_End)
            {
                m_bezileItemList.append((QGraphicsEllipseItem*)item);
                m_scene->removeItem(item);
            }
        }

        qDebug()<<"m_bezileItemList="<<m_bezileItemList.length();
    }

    qDebug()<<"sssssssssssssssssssssdfrehytyj";
    m_RobotItem = new TM_RobotItem(g_RobotChassisLength/(g_map_resolution*100),g_RobotChassisWidth/(g_map_resolution*100),g_RobotChassisRadius/(g_map_resolution*100));//x,y 为左上角的图元局部坐标，图元中心点为0,0
    m_RobotItem->setData(ItemId,"RobotView");
    m_scene->addItem(m_RobotItem);

}

void MyGraphicsView::on_setMapYaml(QString yamlPath)
{
    qDebug()<<"MyGraphicsView::on_setMapYaml="<<yamlPath;
    QFile file(yamlPath);
    if (file.open(QIODevice::ReadOnly | QIODevice::Text))
    {
        QTextStream in(&file);
        while (!in.atEnd()) {
            // 处理每一行的内容
            QString line = in.readLine();
            line = line.replace(" ","");
            //qDebug()<<"line="<<line;
            if(line.contains("image:"))
            {
                g_map_Image = line.right(line.length()-line.indexOf(":")-1);
            }
            else if(line.contains("resolution:"))
            {
                QString data = line.right(line.length()-line.indexOf(":")-1);
                g_map_resolution = data.toDouble();
            }
            else if(line.contains("origin:"))
            {
                QString data = line.right(line.length()-line.indexOf(":")-1);
                data = data.replace("[","");
                data = data.replace("]","");
                QStringList dataList = data.split(",");
                if(dataList.length() >= 3)
                {
                    g_map_origin[0] = QString(dataList[0]).toDouble();
                    g_map_origin[1] = QString(dataList[1]).toDouble();
                    g_map_origin[2] = QString(dataList[2]).toDouble();
                }
            }
        }
        qDebug()<<".yaml="<<g_map_Image<<g_map_resolution<<g_map_origin[0]<<g_map_origin[1]<<g_map_origin[2];
    }
    file.close();
}

void MyGraphicsView::on_setPixmap(QPixmap image,QString PixmapID)
{
    qDebug()<<"MyGraphicsView::on_setPixmap:"<<PixmapID;
    if(m_PixmapItem && m_scene->items().contains(m_PixmapItem))
        m_scene->removeItem(m_PixmapItem);
    if(m_scene->items().size())
    {
        m_scene->clear();
        QMatrix q;
        q.setMatrix(1, this->matrix().m12(),
                    this->matrix().m21(), 1,
                    this->matrix().dx(),
                    this->matrix().dy());
        this->setMatrix(q,false);
        g_curScaleValue = 1;
    }
    g_CurrentMapID = PixmapID;

    m_pixmap = image;
    m_PixmapItem->setPixmap(m_pixmap);
    m_PixmapItem->setFlags(QGraphicsItem::ItemIsSelectable
                          | QGraphicsItem::ItemIsFocusable);
    m_PixmapItem->setPos(0,0);
    m_PixmapItem->setZValue(0);
    m_PixmapItem->setData(ItemId,g_CurrentMapID);
    m_PixmapItem->setData(ItemDesciption,"map");
    m_scene->addItem(m_PixmapItem);
    qDebug()<<"m_PixmapItem.x="<<m_PixmapItem->x()<<m_PixmapItem->y();
    emit sig_MapEditPixmap(m_pixmap,"");
    this->setSceneRect(0, 0, this->width(), this->height());
}

void MyGraphicsView::on_setPointLine(QString JsonPath)
{
    QFile file(JsonPath);
    if(!file.open(QIODevice::ReadOnly | QIODevice::Text))
    {
        qWarning() << "打开文件失败！";
        return;
    }

    // 读取json数据
    QByteArray arr = file.readAll();
    file.close();
    if(arr.isEmpty()) return;

    QJsonParseError err;
    QJsonDocument mdocument = QJsonDocument::fromJson(arr, &err);
    if(!mdocument.isEmpty())   // 如果加载json数据失败则打印失败信息
    {
        QJsonObject dataMap=mdocument.object();
        QJsonArray PointList = dataMap["TMPoint"].toArray();
        QJsonArray LineList = dataMap["TMLine"].toArray();
        QJsonArray BezierPointList = dataMap["TMBezierLineList"].toArray();
        //加载地图时，场景的零点和视图的零点重合
        for (const QJsonValue &value : PointList)
        {
            QJsonObject pointMap = value.toObject();
            TM_RectItem   *item = new TM_RectItem(g_RobotChassisLength/(g_map_resolution*100),g_RobotChassisWidth/(g_map_resolution*100),g_RobotChassisRadius/(g_map_resolution*100),pointMap["ItemId"].toString(),g_is_OpenMapEdit);//x,y 为左上角的图元局部坐标，图元中心点为0,0

            item->setPos(on_X_calibration(false,double(pointMap["ItemX"].toDouble()/g_map_resolution)),on_Y_calibration(false,double(pointMap["ItemY"].toDouble()/g_map_resolution)));
            item->setRotation(-pointMap["ItemRotation"].toDouble());
            item->setData(ItemId,pointMap["ItemId"].toString());
            item->setData(ItemDesciption,pointMap["ItemDesciption"].toString());
            item->setSelected(true);

            m_scene->addItem(item);
            m_scene->clearSelection();
        }
        for (const QJsonValue &value : LineList)
        {
            QJsonObject LineMap = value.toObject();
            QGraphicsItem *startItem;
            QGraphicsItem *endItem;
            foreach(QGraphicsItem  *item,m_scene->items())
            {
                if(item->data(ItemDesciption).toString() == ItemDesciption_Point && item->data(ItemId).toString() == LineMap["ItemLineStartItem"].toString())
                {
                    startItem = item;
                }
                if(item->data(ItemDesciption).toString() == ItemDesciption_Point && item->data(ItemId).toString() == LineMap["ItemLineEndItem"].toString())
                {
                    endItem = item;
                }
            }
            QPointF  start,end,bezierStart,bezierEnd;
            start.setX(startItem->pos().x());
            start.setY(startItem->pos().y());
            end.setX(endItem->pos().x());
            end.setY(endItem->pos().y());

            QString str = LineMap[ItemBezier_Strat].toString();
            if (str.indexOf(',') != -1) {
                bezierStart.setX(on_X_calibration(false,double(str.left(str.indexOf(',')).toDouble()/g_map_resolution)));
                bezierStart.setY(on_Y_calibration(false,double(str.mid(str.indexOf(',') + 1).toDouble()/g_map_resolution)));
            }
            str = LineMap[ItemBezier_End].toString();
            if (str.indexOf(',') != -1) {
                bezierEnd.setX(on_X_calibration(false,double(str.left(str.indexOf(',')).toDouble()/g_map_resolution)));
                bezierEnd.setY(on_Y_calibration(false,double(str.mid(str.indexOf(',') + 1).toDouble()/g_map_resolution)));
            }


            TM_PointLineItem *item = new TM_PointLineItem(start,end,startItem->data(ItemId).toString(),endItem->data(ItemId).toString(),LineMap["ItemLineDirection"].toInt());
            item->setPos(start.x(),start.y());
            item->setData(ItemId,LineMap["ItemId"].toString());
            item->setData(ItemDesciption,LineMap["ItemDesciption"].toString());
            item->setData(ItemLineStartItem,LineMap["ItemLineStartItem"].toString());
            item->setData(ItemLineEndItem,LineMap["ItemLineEndItem"].toString());
            item->setData(ItemStraightLine,LineMap["ItemLineStraight"].toBool());

            for (const QJsonValue &value : BezierPointList)
            {
                QJsonObject LinePoint = value.toObject();
                if(LinePoint["LineID"].toString() == LineMap["ItemId"].toString())
                {
                    QJsonArray LineDirectList = LinePoint["LineDirect"].toArray();
                    for (const QJsonValue &LineDirectvalue : LineDirectList)
                    {
                        QJsonObject LineDirect = LineDirectvalue.toObject();
                        {
                            if(LineDirect["Type"].toString() == "start->end")
                            {
                                for(QJsonObject::iterator it = LineDirect.begin(); it != LineDirect.end(); ++it) {
                                    QString key = it.key();
                                    QJsonValue value = it.value();
                                    item->m_startToend.map[key] = value.toVariant();
                                    //qDebug()<<"122222222222222222"<<key<<value.toString()<<item->m_startToend.map[key].toString();
                                }

                            }
                            else if(LineDirect["Type"].toString() == "end->start")
                            {
                                for(QJsonObject::iterator it = LineDirect.begin(); it != LineDirect.end(); ++it) {
                                    QString key = it.key();
                                    QJsonValue value = it.value();
                                    item->m_endTostart.map[key] = value.toVariant();
                                    //qDebug()<<"122222222222222223"<<key<<value.toString()<<item->m_startToend.map[key].toString();
                                }
                            }
                        }
                    }
                }
            }

            item->setSelected(true);
            item->setBezierPoint(start,end,bezierStart,bezierEnd);
            m_scene->addItem(item);

            QGraphicsEllipseItem   *Ellipse_start=new QGraphicsEllipseItem(-2,-2,4,4);
            Ellipse_start->setFlags(QGraphicsItem::ItemIsMovable
                           | QGraphicsItem::ItemIsSelectable
                           | QGraphicsItem::ItemIsFocusable);
            Ellipse_start->setFlag(QGraphicsItem::ItemIsMovable,true);
            Ellipse_start->setBrush(QBrush(Qt::cyan));
            Ellipse_start->setPen(QPen(Qt::black, 0));
            Ellipse_start->setZValue(3);
            Ellipse_start->setPos(bezierStart);
            Ellipse_start->setData(ItemId,LineMap["ItemId"].toString()+ItemBezier_Strat);
            Ellipse_start->setData(ItemBezierLineID,LineMap["ItemId"].toString());
            Ellipse_start->setData(ItemDesciption,ItemBezier_Strat);
            Ellipse_start->setData(ItemBezierPointID,LineMap["ItemLineStartItem"].toString()
                                   +"->"+LineMap["ItemLineEndItem"].toString());

            QGraphicsEllipseItem   *Ellipse_end=new QGraphicsEllipseItem(-2,-2,4,4);
            Ellipse_end->setFlags(QGraphicsItem::ItemIsMovable
                              | QGraphicsItem::ItemIsSelectable
                              | QGraphicsItem::ItemIsFocusable);
            Ellipse_end->setFlag(QGraphicsItem::ItemIsMovable,true);
            Ellipse_end->setBrush(QBrush(Qt::cyan));
            Ellipse_end->setPen(QPen(Qt::black, 0));
            Ellipse_end->setZValue(3);
            Ellipse_end->setPos(bezierEnd);
            Ellipse_end->setData(ItemId,LineMap["ItemId"].toString()+ItemBezier_End);
            Ellipse_end->setData(ItemBezierLineID,LineMap["ItemId"].toString());
            Ellipse_end->setData(ItemDesciption,ItemBezier_End);
            Ellipse_end->setData(ItemBezierPointID,LineMap["ItemLineStartItem"].toString()
                                                   +"->"+LineMap["ItemLineEndItem"].toString());

            m_scene->addItem(Ellipse_start);
            m_scene->addItem(Ellipse_end);
            m_scene->clearSelection();
            item->setSelected(true);

        }

    }
}

void MyGraphicsView::on_UpdateLine(QGraphicsItem* Pointitem)
{
    if(Pointitem->data(ItemDesciption).toString() == ItemDesciption_Point)
    {
        foreach(QGraphicsItem  *Lineitem,m_scene->items())
        {
            if(Lineitem->data(ItemDesciption).toString() == ItemDesciption_Line)
            {
                if(Lineitem->data(ItemLineStartItem).toString() == Pointitem->data(ItemId).toString())
                {
                    TM_PointLineItem *myLineitem = (TM_PointLineItem*)Lineitem;
                    QPointF  pintStrat,pintEnd,bezierStart,bezierEnd;
                    pintStrat.setX(Pointitem->pos().x());
                    pintStrat.setY(Pointitem->pos().y());
                    myLineitem->setPos(Pointitem->pos().x(),Pointitem->pos().y());

                    QString endItemStr = Lineitem->data(ItemLineEndItem).toString();
                    foreach(QGraphicsItem  *Point_item,m_scene->items())//获取最新结束点的数据
                    {
                        if(Point_item->data(ItemId).toString() == endItemStr && Point_item->data(ItemDesciption).toString() == ItemDesciption_Point)
                        {
                            pintEnd.setX(Point_item->pos().x());
                            pintEnd.setY(Point_item->pos().y());
                            break;
                        }
                    }
                    foreach(QGraphicsItem  *Point_item,m_scene->items())//获取最新开始点bezier的数据
                    {
                        if(Point_item->data(ItemBezierLineID).toString() == Lineitem->data(ItemId).toString()
                            && Point_item->data(ItemDesciption).toString() == ItemBezier_Strat)
                        {
                            bezierStart.setX(Point_item->pos().x());
                            bezierStart.setY(Point_item->pos().y());
                            break;
                        }
                    }
                    foreach(QGraphicsItem  *Point_item,m_scene->items())//获取最新结束点bezier的数据
                    {
                        if(Point_item->data(ItemBezierLineID).toString() == Lineitem->data(ItemId).toString()
                            && Point_item->data(ItemDesciption).toString() == ItemBezier_End)
                        {
                            bezierEnd.setX(Point_item->pos().x());
                            bezierEnd.setY(Point_item->pos().y());
                            break;
                        }
                    }

                    myLineitem->setBezierPoint(pintStrat-m_PixmapItem->pos(),pintEnd-m_PixmapItem->pos(),bezierStart-m_PixmapItem->pos(),bezierEnd-m_PixmapItem->pos());
                    //qDebug()<<"Line——Move start:"<<Pointitem->pos().x()<<Pointitem->pos().y();
                }
                else if(Lineitem->data(ItemLineEndItem).toString() == Pointitem->data(ItemId).toString())
                {
                    TM_PointLineItem *myLineitem = (TM_PointLineItem*)Lineitem;

                    QPointF  pintStrat,pintEnd,bezierStart,bezierEnd;
                    pintEnd.setX(Pointitem->pos().x());
                    pintEnd.setY(Pointitem->pos().y());

                    QString startItemStr = Lineitem->data(ItemLineStartItem).toString();
                    foreach(QGraphicsItem  *Point_item,m_scene->items())//获取最新开始点的数据
                    {
                        if(Point_item->data(ItemId).toString() == startItemStr && Point_item->data(ItemDesciption).toString() == ItemDesciption_Point)
                        {
                            pintStrat.setX(Point_item->pos().x());
                            pintStrat.setY(Point_item->pos().y());
                            break;
                        }
                    }
                    foreach(QGraphicsItem  *Point_item,m_scene->items())//获取最新开始点bezier的数据
                    {
                        if(Point_item->data(ItemBezierLineID).toString() == Lineitem->data(ItemId).toString()
                            && Point_item->data(ItemDesciption).toString() == ItemBezier_Strat)
                        {
                            bezierStart.setX(Point_item->pos().x());
                            bezierStart.setY(Point_item->pos().y());
                            break;
                        }
                    }
                    foreach(QGraphicsItem  *Point_item,m_scene->items())//获取最新结束点bezier的数据
                    {
                        if(Point_item->data(ItemBezierLineID).toString() == Lineitem->data(ItemId).toString()
                            && Point_item->data(ItemDesciption).toString() == ItemBezier_End)
                        {
                            bezierEnd.setX(Point_item->pos().x());
                            bezierEnd.setY(Point_item->pos().y());
                            break;
                        }
                    }
                    myLineitem->setBezierPoint(pintStrat-m_PixmapItem->pos(),pintEnd-m_PixmapItem->pos(),bezierStart-m_PixmapItem->pos(),bezierEnd-m_PixmapItem->pos());
                    //qDebug()<<"Line——Move end:"<<Pointitem->pos().x()<<Pointitem->pos().y();
                }
            }
        }
    }

    else if(Pointitem->data(ItemDesciption).toString() == ItemBezier_Strat)
    {
        QString lineID = Pointitem->data(ItemBezierLineID).toString();
        foreach(QGraphicsItem  *Lineitem,m_scene->items())
        {
            if(Lineitem->data(ItemDesciption).toString() == ItemDesciption_Line && Lineitem->data(ItemId).toString() == lineID)
            {
                TM_PointLineItem *myLineitem = (TM_PointLineItem*)Lineitem;

                QPointF  pintStrat,pintEnd,bezierStart,bezierEnd;
                bezierStart.setX(Pointitem->pos().x());
                bezierStart.setY(Pointitem->pos().y());

                foreach(QGraphicsItem  *Point_item,m_scene->items())//获取最新开始点的数据
                {
                    if(Point_item->data(ItemId).toString() == Lineitem->data(ItemLineStartItem).toString() && Point_item->data(ItemDesciption).toString() == ItemDesciption_Point)
                    {
                        pintStrat.setX(Point_item->pos().x());
                        pintStrat.setY(Point_item->pos().y());
                        break;
                    }
                }
                foreach(QGraphicsItem  *Point_item,m_scene->items())//获取最新结束点的数据
                {
                    if(Point_item->data(ItemId).toString() == Lineitem->data(ItemLineEndItem).toString() && Point_item->data(ItemDesciption).toString() == ItemDesciption_Point)
                    {
                        pintEnd.setX(Point_item->pos().x());
                        pintEnd.setY(Point_item->pos().y());
                        break;
                    }
                }
                foreach(QGraphicsItem  *Point_item,m_scene->items())//获取最新结束点bezier的数据
                {
                    if(Point_item->data(ItemBezierLineID).toString() == Lineitem->data(ItemId).toString()
                        && Point_item->data(ItemDesciption).toString() == ItemBezier_End)
                    {
                        bezierEnd.setX(Point_item->pos().x());
                        bezierEnd.setY(Point_item->pos().y());
                        break;
                    }
                }
                myLineitem->setBezierPoint(pintStrat-m_PixmapItem->pos(),pintEnd-m_PixmapItem->pos(),bezierStart-m_PixmapItem->pos(),bezierEnd-m_PixmapItem->pos());
            }
        }
    }

    else if(Pointitem->data(ItemDesciption).toString() == ItemBezier_End)
    {
        QString lineID = Pointitem->data(ItemBezierLineID).toString();
        foreach(QGraphicsItem  *Lineitem,m_scene->items())
        {
            if(Lineitem->data(ItemDesciption).toString() == ItemDesciption_Line && Lineitem->data(ItemId).toString() == lineID)
            {
                TM_PointLineItem *myLineitem = (TM_PointLineItem*)Lineitem;

                QPointF  pintStrat,pintEnd,bezierStart,bezierEnd;
                bezierEnd.setX(Pointitem->pos().x());
                bezierEnd.setY(Pointitem->pos().y());

                foreach(QGraphicsItem  *Point_item,m_scene->items())//获取最新开始点的数据
                {
                    if(Point_item->data(ItemId).toString() == Lineitem->data(ItemLineStartItem).toString() && Point_item->data(ItemDesciption).toString() == ItemDesciption_Point)
                    {
                        pintStrat.setX(Point_item->pos().x());
                        pintStrat.setY(Point_item->pos().y());
                        break;
                    }
                }
                foreach(QGraphicsItem  *Point_item,m_scene->items())//获取最新结束点的数据
                {
                    if(Point_item->data(ItemId).toString() == Lineitem->data(ItemLineEndItem).toString() && Point_item->data(ItemDesciption).toString() == ItemDesciption_Point)
                    {
                        pintEnd.setX(Point_item->pos().x());
                        pintEnd.setY(Point_item->pos().y());
                        break;
                    }
                }
                foreach(QGraphicsItem  *Point_item,m_scene->items())//获取最新开始点bezier的数据
                {
                    if(Point_item->data(ItemBezierLineID).toString() == Lineitem->data(ItemId).toString()
                        && Point_item->data(ItemDesciption).toString() == ItemBezier_Strat)
                    {
                        bezierStart.setX(Point_item->pos().x());
                        bezierStart.setY(Point_item->pos().y());
                        break;
                    }
                }
                myLineitem->setBezierPoint(pintStrat-m_PixmapItem->pos(),pintEnd-m_PixmapItem->pos(),bezierStart-m_PixmapItem->pos(),bezierEnd-m_PixmapItem->pos());

            }
        }
    }
}

double MyGraphicsView::on_X_calibration(bool isSave, double value)
{
    double data;
    if(isSave)
        data = double(value+(g_map_origin[0]/g_map_resolution));
    else
        data = double(value-(g_map_origin[0]/g_map_resolution));
    return (int)(data*1000)/1000.0;
}

double MyGraphicsView::on_Y_calibration(bool isSave, double value)
{
    double data;
    if(isSave)
        data = double(m_pixmap.height()-value+(g_map_origin[1]/g_map_resolution));
    else
        data = double(m_pixmap.height()-value+(g_map_origin[1]/g_map_resolution));
    return (int)(data*1000)/1000.0;
}

void MyGraphicsView::slot_OpenMapEdit(bool isOpen)
{
    g_is_OpenMapEdit = isOpen;
    if(g_is_OpenMapEdit)
    {
        foreach(QGraphicsEllipseItem  *item,m_bezileItemList)
        {
            m_scene->addItem(item);
        }
    }
    else
    {
        m_bezileItemList.clear();
        QList<QGraphicsItem*>itemList = m_scene->items();
        foreach(QGraphicsItem  *item,itemList)
        {
            if(item->data(ItemDesciption).toString() == ItemBezier_Strat
                || item->data(ItemDesciption).toString() == ItemBezier_End)
            {
                m_bezileItemList.append((QGraphicsEllipseItem*)item);
                m_scene->removeItem(item);
            }
        }
    }

    qDebug()<<"MyGraphicsView::slot_OpenMapEdit="<<g_is_OpenMapEdit;
    this->viewport()->update();
}

void MyGraphicsView::slot_LinerAutoSetBazierPos(QGraphicsItem *Pointitem)
{
    //直线自动调整bazier焦点
    if(Pointitem->data(ItemDesciption).toString() == ItemDesciption_Point)
    {
        foreach(QGraphicsItem  *Lineitem,m_scene->items())
        {
            if(Lineitem->data(ItemDesciption).toString() == ItemDesciption_Line)
            {
                if((Lineitem->data(ItemLineStartItem).toString() == Pointitem->data(ItemId).toString()
                     || Lineitem->data(ItemLineEndItem).toString() == Pointitem->data(ItemId).toString())
                    && Lineitem->data(ItemStraightLine).toBool())
                {
                    foreach(QGraphicsItem  *Point_item,m_scene->items())
                    {
                        if((Point_item->data(ItemDesciption).toString() == ItemBezier_End
                             ||Point_item->data(ItemDesciption).toString() == ItemBezier_Strat))
                        {
                            if(Point_item->data(ItemBezierLineID).toString() == Lineitem->data(ItemId).toString())
                            {
                                qreal x,x1,y,y1;

                                foreach(QGraphicsItem  *Point_item01,m_scene->items())
                                {
                                    if(Lineitem->data(ItemLineStartItem).toString() == Point_item01->data(ItemId).toString())
                                    {
                                        x = Point_item01->x();
                                        y = Point_item01->y();
                                    }
                                    else if(Lineitem->data(ItemLineEndItem).toString() == Point_item01->data(ItemId).toString())
                                    {
                                        x1 = Point_item01->x();
                                        y1 = Point_item01->y();
                                    }
                                }

                                Point_item->setPos((x1+x)/2,(y1+y)/2);
                            }
                        }
                    }
                }
            }


        }
    }

    else if(Pointitem->data(ItemDesciption).toString() == ItemBezier_Strat
             || Pointitem->data(ItemDesciption).toString() == ItemBezier_End)
    {
        foreach(QGraphicsItem  *Lineitem,m_scene->items())
        {
            if(Lineitem->data(ItemDesciption).toString() == ItemDesciption_Line
                && Lineitem->data(ItemId).toString() ==  Pointitem->data(ItemBezierLineID).toString()
                && Lineitem->data(ItemStraightLine).toBool())
            {
                foreach(QGraphicsItem  *Point_item,m_scene->items())
                {
                    if((Point_item->data(ItemDesciption).toString() == ItemBezier_End
                         ||Point_item->data(ItemDesciption).toString() == ItemBezier_Strat))
                    {
                        if(Point_item->data(ItemBezierLineID).toString() == Pointitem->data(ItemBezierLineID).toString())
                        {
                            qreal x,x1,y,y1;

                            foreach(QGraphicsItem  *Point_item01,m_scene->items())
                            {
                                if(Lineitem->data(ItemLineStartItem).toString() == Point_item01->data(ItemId).toString())
                                {
                                    x = Point_item01->x();
                                    y = Point_item01->y();
                                }
                                else if(Lineitem->data(ItemLineEndItem).toString() == Point_item01->data(ItemId).toString())
                                {
                                    x1 = Point_item01->x();
                                    y1 = Point_item01->y();
                                }
                            }

                            Point_item->setPos((x1+x)/2,(y1+y)/2);
                        }
                    }
                }
            }


        }
    }


}

void MyGraphicsView::slot_Map_Edit(QString Type, QString data)
{
    //qDebug()<<"MyGraphicsView::slot_Map_Edit="<<Type<<data;
    if(Type == "Rotation" || Type == "setPointY" || Type == "setPointX")
    {
        if(m_scene->selectedItems().length() == 1)
        {
            QGraphicsItem* item=m_scene->selectedItems().at(0);
            if(item->data(ItemDesciption).toString() == ItemDesciption_Point)
            {
                if(Type == "Rotation")
                    item->setRotation(data.toInt());
                else if(Type == "setPointX")
                {
                    double PointX = m_PixmapItem->pos().x()+on_X_calibration(false,double(data.toDouble()/g_map_resolution));
                    item->setPos(PointX,item->pos().y());
                }
                else if(Type == "setPointY")
                {
                    double PointY = m_PixmapItem->pos().y()+on_Y_calibration(false,double(data.toDouble()/g_map_resolution));
                    item->setPos(item->pos().x(),PointY);
                }
            }
        }
    }
    else if(Type == "PointName")
    {
        foreach(QGraphicsItem  *pointitem,m_scene->items())
        {
            if(pointitem->data(ItemId).toString() == data)
            {
                return;
            }
        }

        if(m_scene->selectedItems().length() == 1)
        {
            QGraphicsItem* item=m_scene->selectedItems().at(0);
            if(item->data(ItemDesciption).toString() == ItemDesciption_Point)
            {
                foreach(QGraphicsItem  *itemLine,m_scene->items())
                {
                    if(itemLine->data(ItemDesciption).toString() == ItemDesciption_Line)
                    {
                        TM_PointLineItem *Lineitem = (TM_PointLineItem*)itemLine;
                        if(itemLine->data(ItemLineStartItem).toString() == item->data(ItemId).toString())
                        {
                            itemLine->setData(ItemLineStartItem,data);
                            if(Lineitem->m_LineDirection == 1 || Lineitem->m_LineDirection == 3)
                            {
                                Lineitem->m_startToend.map["start"] = data;
                            }
                            if(Lineitem->m_LineDirection == 2 || Lineitem->m_LineDirection == 3)
                            {
                                Lineitem->m_endTostart.map["end"] = data;
                            }
                        }
                        if(itemLine->data(ItemLineEndItem).toString() == item->data(ItemId).toString())
                        {
                            itemLine->setData(ItemLineEndItem,data);
                            if(Lineitem->m_LineDirection == 1 || Lineitem->m_LineDirection == 3)
                            {
                                Lineitem->m_startToend.map["end"] = data;
                            }
                            if(Lineitem->m_LineDirection == 2 || Lineitem->m_LineDirection == 3)
                            {
                                Lineitem->m_endTostart.map["start"] = data;
                            }
                        }





                    }
                }

                TM_RectItem *rectitem = (TM_RectItem*)item;
                rectitem->m_Text = data;
                rectitem->setData(ItemId,data);
                this->viewport()->update();
            }
        }
    }

    else if(Type == "ItemViewCenter")
    {
        QPointF pointStart,pointEnd;
        foreach(QGraphicsItem  *item,m_scene->items())
        {
            if(item->data(ItemId).toString() == data)
            {
                pointStart = item->pos();
                pointEnd = QPointF(this->width()/2,this->height()/2);
                QPointF point = pointEnd - pointStart;

                foreach(QGraphicsItem  *item,m_scene->items())
                {
                    if(item->data(ItemDesciption).toString() != ItemBezier_Direct)
                        item->moveBy(point.x(), point.y());
                }
                if(!g_is_OpenMapEdit)
                {
                    foreach(QGraphicsEllipseItem  *item,m_bezileItemList)
                        item->moveBy(point.x(), point.y());
                }
                break;
            }
        }
    }
    else if(Type == "DelPoint" || Type == "DelLine" || Type == "DelPointLine")
    {
        if(m_scene->selectedItems().length()==1)
        {
            QGraphicsItem* item=m_scene->selectedItems().at(0);
            if(item->data(ItemDesciption).toString() == ItemDesciption_Point
                && (Type == "DelPoint" || Type == "DelPointLine"))
            {
                QList<QGraphicsItem*> m_itrmList = m_scene->items();
                for(int itor = m_itrmList.length() - 1; itor >= 0; itor--)
                {
                    QGraphicsItem *Lineitem = (QGraphicsItem*)m_itrmList[itor];
                    qDebug()<<"--------"<<Lineitem->data(ItemDesciption).toString()<<Lineitem->data(ItemBezierPointID).toString()<<item->data(ItemId).toString();
                    if(Lineitem->data(ItemDesciption).toString() == ItemDesciption_Line)
                    {
                        if(Lineitem->data(ItemLineStartItem).toString() == item->data(ItemId).toString())
                        {
                            m_scene->removeItem(Lineitem);
                            continue;
                        }
                        else if(Lineitem->data(ItemLineEndItem).toString() == item->data(ItemId).toString())
                        {
                            m_scene->removeItem(Lineitem);
                            continue;
                        }
                    }
                    else if(Lineitem->data(ItemDesciption).toString() == ItemBezier_Strat
                        || Lineitem->data(ItemDesciption).toString() == ItemBezier_End)
                    {
                        QString bezierPoint = Lineitem->data(ItemBezierPointID).toString();
                        if(bezierPoint.indexOf(item->data(ItemId).toString()) != -1)
                        {
                            m_scene->removeItem(Lineitem);
                            continue;
                        }
                    }

                }
                for(int itor = m_itrmList.length() - 1; itor >= 0; itor--)
                {
                    QGraphicsItem *Pointitem = (QGraphicsItem*)m_itrmList[itor];
                    if(Pointitem->data(ItemId).toString() == item->data(ItemId).toString())
                    {
                        m_scene->removeItem(Pointitem);
                    }
                }
            }

            if((item->data(ItemDesciption).toString() == ItemBezier_Strat
                 || item->data(ItemDesciption).toString() == ItemBezier_End)
                && (Type == "DelLine" || Type == "DelPointLine")
                )
            {
                QList<QGraphicsItem*> m_itrmList = m_scene->items();
                for(int itor = m_itrmList.length() - 1; itor >= 0; itor--)
                {
                    QGraphicsItem *Lineitem = (QGraphicsItem*)m_itrmList[itor];
                    if(Lineitem->data(ItemDesciption).toString() == ItemDesciption_Line
                        && Lineitem->data(ItemId).toString() == item->data(ItemBezierLineID).toString())
                    {
                        m_scene->removeItem(Lineitem);
                        continue;
                    }
                    else if((Lineitem->data(ItemDesciption).toString() == ItemBezier_Strat
                              || Lineitem->data(ItemDesciption).toString() == ItemBezier_End)
                             && Lineitem->data(ItemBezierLineID).toString() == item->data(ItemBezierLineID).toString())
                    {
                        m_scene->removeItem(Lineitem);
                        continue;
                    }
                }
            }
        }
    }

    else if(Type == "robotshow")
    {
        is_RobotAddScan = data == "true";
        m_RobotItem->setVisible(is_RobotAddScan);
    }
    else if(Type == "LineDirect"
             || Type == "StraightLine"
                ||Type.contains(":end->start")
                || Type.contains(":start->end"))
    {
        if(m_scene->selectedItems().length() == 1)
        {
            QGraphicsItem* item=m_scene->selectedItems().at(0);
            if(item->data(ItemDesciption).toString() == ItemBezier_Strat
                || item->data(ItemDesciption).toString() == ItemBezier_End)
            {
                QList<QGraphicsItem*> m_itrmList = m_scene->items();
                for(int itor = m_itrmList.length() - 1; itor >= 0; itor--)
                {
                    TM_PointLineItem *Lineitem = (TM_PointLineItem*)m_itrmList[itor];
                    if(Lineitem->data(ItemId).toString() == item->data(ItemBezierLineID).toString())
                    {
                        if(Type == "LineDirect")
                        {
                            Lineitem->setLineDerice(data.toInt());
                        }
                        else if(Type == "StraightLine")
                        {
                            Lineitem->setData(ItemStraightLine,data);
                            slot_LinerAutoSetBazierPos(item);
                            on_UpdateLine(item);//更新路线
                        }
                        else if((Type.contains(":end->start") || Type.contains(":start->end"))
                                   && Type.endsWith(Lineitem->data(ItemId).toString()))
                        {
                            Lineitem->setLine_Parameter(Type.left(Type.indexOf(Lineitem->data(ItemId).toString())),data);
                        }

                        QVariantMap dataMap;
                        dataMap["LineitemID"] = Lineitem->data(ItemId).toString();
                        dataMap["ItemBezierPointID"] = Lineitem->data(ItemLineStartItem).toString()+"->"+Lineitem->data(ItemLineEndItem).toString();
                        // 使用QMap的constBegin()和constEnd()遍历

                        QVariantMap StartEndMap;
                        for (QVariantMap::const_iterator it = Lineitem->m_startToend.map.constBegin(); it != Lineitem->m_startToend.map.constEnd(); ++it) {
                            StartEndMap[it.key()] = it.value().toString();
                        }
                        dataMap["StartEnd"] = StartEndMap;
                        QVariantMap EndStartMap;
                        for (QVariantMap::const_iterator it = Lineitem->m_endTostart.map.constBegin(); it != Lineitem->m_endTostart.map.constEnd(); ++it) {
                            EndStartMap[it.key()] = it.value().toString();
                        }
                        dataMap["EndStart"] = EndStartMap;
                        dataMap["StraightLine"] = Lineitem->data(ItemStraightLine).toBool();
                        dataMap["LineDirection"] = Lineitem->m_LineDirection;
                        emit sig_MapLineMessage("Moucebezier",dataMap);
                    }
                }
            }
        }
    }



    else if(Type == "newMapEdit")
    {
        if(data == "startCreateMap" || data == "stopCreateMap")
        {
            if(data == "startCreateMap")
            {
                g_is_OpenCreateMap = true;
                on_LoadMapfilePath("CreateNewMap");
                QPixmap pixmap;
                if(m_RobotItem)
                {
                    if(m_scene->items().contains(m_RobotItem))
                    {
                        m_scene->removeItem(m_RobotItem);
                    }
                }
                on_setPixmap(pixmap,data);

                if(m_RobotItem)
                    m_scene->addItem(m_RobotItem);

            }
            else
                g_is_OpenCreateMap = false;
        }
    }

    update();
}

void MyGraphicsView::slot_CurrentAction(int ActionType,QString data)
{
    m_CurrentAction = ActionType;
    qDebug()<<"m_CurrentAction="<<m_CurrentAction<<g_is_OpenMapEdit<<data;
    foreach(QGraphicsItem  *Point_item,m_scene->items())
    {
        if(Point_item->data(ItemDesciption).toString() == ItemDesciption_Point)
        {
            Point_item->setFlag(QGraphicsItem::ItemIsMovable,m_CurrentAction == Action_NULL && g_is_OpenMapEdit);
        }
    }

    if(m_CurrentAction == Action_Eraser || m_CurrentAction == Action_VirtualWall)
    {
        if(!m_pixmap.isNull())
            emit sig_MapEditPixmap(m_pixmap,data);
    }
}

void MyGraphicsView::slot_SaveMap(QString Path)
{
    qDebug()<<" MyGraphicsView::slot_SaveMap(QString Path)--------------------------"<<QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss:zzz");;

    QDir dir(Path);
    if (!dir.exists())
    {
        dir.mkpath(Path);
    }

    foreach(QGraphicsItem  *bezierPoint_item,m_scene->items())//获取最新结束点的数据
    {
        if(bezierPoint_item->data(ItemDesciption).toString() == ItemBezier_Strat)
        {
            on_UpdateLine(bezierPoint_item);
        }
    }

    savePixmapAsPgm(m_pixmap,QString("%1/%2.pgm").arg(Path).arg(g_CurrentMapID));


    QJsonArray PointList;
    QJsonArray LineList;
    QJsonArray BezierList;

    foreach(QGraphicsItem  *item,m_scene->items())
    {
        if(item->data(ItemDesciption).toString() == ItemDesciption_Point)
        {
            QJsonObject PointMap;
            PointMap["ItemId"] = item->data(ItemId).toString();
            PointMap["ItemDesciption"] = item->data(ItemDesciption).toString();
            PointMap["ItemRotation"] = -item->rotation();
            QPointF pointClicl = (item->pos() - m_PixmapItem->pos());
            //qDebug()<<"save--"<<double(on_X_calibration(true,pointClicl.x())*g_map_resolution)<<double(on_Y_calibration(true,pointClicl.y())*g_map_resolution);
            PointMap["ItemX"] = double(on_X_calibration(true,pointClicl.x())*g_map_resolution);
            PointMap["ItemY"] = double(on_Y_calibration(true,pointClicl.y())*g_map_resolution);
            PointMap["ItemZ"] = item->zValue();
            PointList.append(PointMap);

        }

        else if(item->data(ItemDesciption).toString() == ItemDesciption_Line)
        {
            //保存路线信息
            TM_PointLineItem *myLineitem = (TM_PointLineItem*)item;
            QJsonObject LineMap;
            LineMap["ItemId"] = myLineitem->data(ItemId).toString();
            LineMap["ItemDesciption"] = myLineitem->data(ItemDesciption).toString();
            LineMap["ItemLineStartItem"] =  myLineitem->data(ItemLineStartItem).toString();
            LineMap["ItemLineEndItem"] =  myLineitem->data(ItemLineEndItem).toString();
            LineMap["ItemLineDirection"] = myLineitem->m_LineDirection;
            LineMap["ItemLineStraight"] = myLineitem->data(ItemStraightLine).toBool();

            QList<QGraphicsItem *> itemsList = m_scene->items();;

            if(!g_is_OpenMapEdit)
            {
                for(int i=0;i<m_bezileItemList.length();i++)
                    itemsList.append((QGraphicsItem *)m_bezileItemList[i]);
            }
            foreach(QGraphicsItem  *itembezier,itemsList)
            {
                //qDebug()<<"save================"<<myLineitem->data(ItemDesciption).toString()<<myLineitem->data(ItemBezierLineID).toString()<<myLineitem->data(ItemId).toString();
                //保存相对于场景Scane的位置
                if((itembezier->data(ItemDesciption).toString() == ItemBezier_Strat || itembezier->data(ItemDesciption).toString() == ItemBezier_End)
                    && itembezier->data(ItemBezierLineID).toString() == myLineitem->data(ItemId).toString())
                {
                    QString keystr = itembezier->data(ItemDesciption).toString();
                    QPointF pointClicl = (itembezier->pos() - m_PixmapItem->pos());
                    LineMap[keystr] = QString("%1,%2").arg(double(on_X_calibration(true,pointClicl.x())*g_map_resolution))
                                                      .arg(double(on_Y_calibration(true,pointClicl.y())*g_map_resolution));
                }
            }

            //保存bezier路线点位信息

            double m_LineLen = 0;
            QJsonObject bezierMap;
            bezierMap["ItemLineStraight"] = myLineitem->data(ItemStraightLine).toBool();
            bezierMap["LineID"] = myLineitem->data(ItemId).toString();
            QJsonArray jsonArray;
            for (int i = 0; i < myLineitem->m_PointList.length(); ++i)
            {
                QPointF datapoint = QPointF(myLineitem->m_PointList[i]);
                QJsonArray innerArray;
                innerArray.append(QJsonValue(double(on_X_calibration(true,datapoint.x())*g_map_resolution)));
                innerArray.append(QJsonValue(double(on_Y_calibration(true,datapoint.y())*g_map_resolution)));

                if(i!=0)
                {
                    QPointF datapoint_end = QPointF(myLineitem->m_PointList[i]);
                    double xPos_end = on_X_calibration(true,datapoint_end.x());
                    double yPos_end = on_Y_calibration(true,datapoint_end.y());
                    QPointF datapoint_start = QPointF(myLineitem->m_PointList[i-1]);
                    double xPos = on_X_calibration(true,datapoint_start.x());
                    double yPos = on_Y_calibration(true,datapoint_start.y());

                    m_LineLen += fabs(sqrt((xPos_end-xPos)*(xPos_end-xPos) + (yPos_end - yPos)*(yPos_end - yPos))) * g_map_resolution;
                }

                jsonArray.append(innerArray);
            }

            LineMap["ItemLineDistance"] = ((float)((int)(m_LineLen * 100))) / 100;
            bezierMap["ALLPoint"] = jsonArray;
            QJsonArray DirectList;
            if(myLineitem->m_LineDirection == 1 || myLineitem->m_LineDirection == 3)
            {
                QJsonObject map;
                map["start"] = myLineitem->data(ItemLineStartItem).toString();
                map["end"] = myLineitem->data(ItemLineEndItem).toString();
                map["Type"] = "start->end";
                for (QVariantMap::const_iterator it = myLineitem->m_startToend.map.constBegin(); it != myLineitem->m_startToend.map.constEnd(); ++it) {
                    //qDebug() << it.key() << ": " << it.value();
                    map[it.key()] = it.value().toString();
                }


                DirectList.append(map);
            }
            if(myLineitem->m_LineDirection == 2 || myLineitem->m_LineDirection == 3)
            {
                QJsonObject map;
                map["start"] = myLineitem->data(ItemLineEndItem).toString();
                map["end"] = myLineitem->data(ItemLineStartItem).toString();
                map["Type"] = "end->start";
                for (QVariantMap::const_iterator it = myLineitem->m_endTostart.map.constBegin(); it != myLineitem->m_endTostart.map.constEnd(); ++it) {
                    //qDebug() << it.key() << ": " << it.value();
                    map[it.key()] = it.value().toString();
                }
                DirectList.append(map);
            }
            bezierMap["LineDirect"] = DirectList;

            LineList.append(LineMap);
            BezierList.append(bezierMap);
        }
    }

    QJsonObject ALLMap;
    ALLMap["JSONVERSION"] = APP_VERSION;
    ALLMap["TMBezierLineList"] = BezierList;
    ALLMap["TMLine"] = LineList;
    ALLMap["TMPoint"] = PointList;
    //QString Str = QString(PublicShared::variant2JsonStr(ALLMap));
    QJsonDocument jsonDoc(ALLMap);
    //根据实际填写路径
    qDebug()<<"QFile file:"<<QString("%1/%2.json").arg(Path).arg(g_CurrentMapID);
    QFile file(QString("%1/%2.json").arg(Path).arg(g_CurrentMapID));

    if (!file.open(QIODevice::ReadWrite | QIODevice::Text |QFile::Truncate))
    {
        qDebug() << "file error!";
    }
    file.resize(0);
    QTextStream in(&file);
    in << jsonDoc.toJson();
    file.close();


    QImage image(m_scene->width(), m_scene->height(), QImage::Format_ARGB32);
    image.fill(Qt::transparent);
    QPainter painter(&image);
    m_scene->render(&painter);
    // 保存图片到本地文件中
    QString filename = QString("%1/%2.png").arg(Path).arg(g_CurrentMapID);
    image.save(filename);


    qDebug()<<" MyGraphicsView::slot_SaveMap end --------------------------"<<QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss:zzz");;

}

bool MyGraphicsView::savePixmapAsPgm(const QPixmap &pixmap, const QString &fileName)
{
    // 确保 pixmap 不为空
    if (pixmap.isNull()) {
        return false;
    }
    QImage image = pixmap.toImage().convertToFormat(QImage::Format_Grayscale8);
    return image.save(fileName);
}

void MyGraphicsView::slot_NaviRosData(QString type, QStringList dataList)
{
    //qDebug()<<"slot_NaviRosData"<<g_CurrentMapID<<g_is_OpenMapEdit<<type;

    if(g_CurrentMapID != "")
    {
        if(type == g_RobotPose && dataList.length() >= 3)
        {
            double x = QString(dataList[0]).toDouble();
            double y = QString(dataList[1]).toDouble();
            double z = QString(dataList[2]).toDouble();
            m_RobotItem->m_x_shift = x/g_map_resolution;
            m_RobotItem->m_y_shift = y/g_map_resolution;
            double PointX = m_PixmapItem->pos().x()+on_X_calibration(false,double(x/g_map_resolution));
            double PointY = m_PixmapItem->pos().y()+on_Y_calibration(false,double(y/g_map_resolution));
            double PointZ = double(z);
            //qDebug()<<"m_RobotItem->setPos="<<x<<y<<z<<PointX<<PointY<<PointZ;

            if(!m_is_ActionIng)
            {
                m_RobotItem->setPos(PointX,PointY);
                m_RobotItem->setRotation(-PointZ);
            }
        }
        else if(type == g_RobotScan_multi)
        {
            m_RobotItem->on_Set_RadirData(g_RobotScan_multi,dataList);
            this->viewport()->update();
        }
    }

}

void MyGraphicsView::slot_mapPixmap(QPixmap pixmap)
{
    qDebug()<<"MyGraphicsView::slot_mapPixmap="<<g_is_OpenCreateMap;
    if(g_is_OpenCreateMap || true)
    {
        m_pixmap = pixmap;
        m_PixmapItem->setPixmap(m_pixmap);
    }
}

void MyGraphicsView::mousePressEvent(QMouseEvent *event)
{
    qDebug()<<"MyGraphicsView::mousePressEvent";
    if(m_PixmapItem == nullptr)
        return;
    qDebug()<<"MyGraphicsView::mousePressEvent01";
    if(event->button()== Qt::LeftButton)
    {
        QPoint  point=event->pos();
        QPointF pointScene=this->mapToScene(point); //转换到Scene坐标
        QGraphicsItem  *item=NULL;
        item=m_scene->itemAt(pointScene,this->transform()); //获取光标下的绘图项

        // qDebug()<<QString::asprintf("View 坐标：%d,%d",point.x(),point.y());
        // qDebug()<<QString::asprintf("Scene 坐标：%.0f,%.0f", pointScene.x(),pointScene.y());

        if (item == NULL) //有绘图项
        {
            return;
        }
        if(item->data(ItemDesciption).toString() == ItemDesciption_Line
            ||item->data(ItemDesciption).toString() == ItemBezier_Direct)
            item = m_PixmapItem;

        qDebug()<<"item != NULL"<<item->data(ItemId).toString()<<item->data(ItemDesciption).toString()<<QString::asprintf("item 坐标：%.0f,%.0f", item->x(),item->y());

        if(m_CurrentAction == Action_AddPoint
            && item->data(ItemDesciption).toString() != ItemDesciption_Point)
        {
            QString PointStrID;
            for(int PintId=1;PintId<=999999;PintId++)
            {
                bool is_Have = false;
                foreach(QGraphicsItem  *item,m_scene->items())
                {
                    if(item->data(ItemDesciption).toString() == ItemDesciption_Point
                        && item->data(ItemId).toString() == QString("LM%1").arg(QString::number(PintId)))
                    {
                        is_Have = true;
                        break;
                    }
                }
                if(!is_Have)
                {
                    PointStrID = QString("LM%1").arg(PintId);
                    break;
                }

            }

            TM_RectItem   *item = new TM_RectItem(g_RobotChassisLength/(g_map_resolution*100),g_RobotChassisWidth/(g_map_resolution*100),g_RobotChassisRadius/(g_map_resolution*100),PointStrID,g_is_OpenMapEdit);//x,y 为左上角的图元局部坐标，图元中心点为0,0
            item->setPos(pointScene.x(),pointScene.y());
            item->setData(ItemId,PointStrID);
            item->setData(ItemDesciption,ItemDesciption_Point);
            item->setSelected(true);
            m_scene->addItem(item);
            m_scene->clearSelection();
        }
        else if(m_CurrentAction == Action_DrawLine)
        {
            if(item->data(ItemDesciption).toString() == ItemDesciption_Point)
            {
                //开始路线绘制
                is_Line_startItem = item;
                is_Xiugai_Line = true;
            }
        }
        else if(m_CurrentAction == Action_mapLocation)
        {
            if(m_RobotItem != NULL)
            {
                QPoint  point=event->pos();
                QPointF pointScene=this->mapToScene(point);
                m_RobotItem->setPos(pointScene.x(),pointScene.y());
                m_RobotItem->setRotation(0);
                m_is_ActionIng = true;
            }
        }
        else if(m_CurrentAction == Action_NULL)
        {
            //非路线绘制，地图拖拽
            m_mousePos = event->pos();
            m_mouseClickItemID = item->data(ItemId).toString();
            if(m_mouseClickItemID == g_CurrentMapID)
            {
                //点击点在地图中的坐标
                QPointF pointItem=item->mapFromScene(pointScene); //转换为绘图项的局部坐标
                QVariantMap dataMap;
                dataMap["clickpoint"] = QString::number(on_X_calibration(true,pointItem.x())*g_map_resolution)+","
                                        +QString::number(on_Y_calibration(true,pointItem.y())*g_map_resolution);

                emit sig_MapLineMessage("MouceCoordinateMess",dataMap);
            }
            else
            {
                QPointF pointClicl = (item->pos() - m_PixmapItem->pos());
                if(item->data(ItemDesciption).toString() == ItemDesciption_Point
                    || item->data(ItemDesciption).toString() == ItemBezier_Strat
                    || item->data(ItemDesciption).toString() == ItemBezier_End)
                {
                    if(item->data(ItemDesciption).toString() == ItemDesciption_Point)
                    {
                        is_Xiugai_Line = true;

                        double x = on_X_calibration(true,pointClicl.x())*g_map_resolution;
                        double y = on_Y_calibration(true,pointClicl.y())*g_map_resolution;
                        QVariantMap dataMap;
                        dataMap["rotation"] = QString::number(item->rotation());
                        dataMap["ItemId"] = item->data(ItemId).toString();
                        dataMap["pointX"] = x;
                        dataMap["pointY"] = y;

                        emit sig_MapLineMessage("MoucePinotMess",dataMap);
                    }
                    else if(item->data(ItemDesciption).toString() == ItemBezier_Strat
                             || item->data(ItemDesciption).toString() == ItemBezier_End)
                    {
                        is_Xiugai_Line = true;
                        QVariantMap dataMap;
                        dataMap["ItemBezierPointID"] = item->data(ItemBezierPointID).toString();
                        dataMap["LineitemID"] = item->data(ItemBezierLineID).toString();
                        QList<QGraphicsItem*> m_itrmList = m_scene->items();
                        for(int itor = m_itrmList.length() - 1; itor >= 0; itor--)
                        {
                            TM_PointLineItem *myLineitem = (TM_PointLineItem*)m_itrmList[itor];
                            if(myLineitem->data(ItemId).toString() == item->data(ItemBezierLineID).toString()
                                && myLineitem->data(ItemDesciption).toString() == ItemDesciption_Line)
                            {
                                QVariantMap StartEndMap;
                                for (QVariantMap::const_iterator it = myLineitem->m_startToend.map.constBegin(); it != myLineitem->m_startToend.map.constEnd(); ++it) {
                                    //qDebug() <<"qwertyuigh"<< it.key() << ": " << it.value().toString();
                                    StartEndMap[it.key()] = it.value().toString();
                                }
                                dataMap["StartEnd"] = StartEndMap;
                                QVariantMap EndStartMap;
                                for (QVariantMap::const_iterator it = myLineitem->m_endTostart.map.constBegin(); it != myLineitem->m_endTostart.map.constEnd(); ++it) {
                                    //qDebug() <<"qwertyuigh__"<< it.key() << ": " << it.value().toString();
                                    EndStartMap[it.key()] = it.value().toString();
                                }
                                dataMap["EndStart"] = EndStartMap;
                                dataMap["StraightLine"] = myLineitem->data(ItemStraightLine).toBool();
                                dataMap["LineDirection"] = myLineitem->m_LineDirection;
                            }
                        }
                        emit sig_MapLineMessage("Moucebezier",dataMap);
                    }
                    //点击的item 中心点在地图中的坐标

                    emit sig_MapMessage("MoucePinot",QString(u8"%1 item(场景)坐标:%2,相对于地图左上点坐标:%3,相对于地图0点坐标:%4").arg(m_mouseClickItemID
                                                          ,QString::asprintf("%.0f,%.0f",item->pos().x(),item->pos().y())
                                                          ,QString::asprintf("%.0f,%.0f",pointClicl.x(),pointClicl.y())
                                                          ,QString::asprintf("%.0f,%.0f", on_X_calibration(true,pointClicl.x()),on_Y_calibration(true,pointClicl.y()))));
                }

            }

        }

    }
    else if(event->button() == Qt::RightButton)
    {

        QPoint  point=event->pos();
        QPointF pointScene=this->mapToScene(point); //转换到Scene坐标
        QGraphicsItem  *item=NULL;
        item=m_scene->itemAt(pointScene,this->transform());
        m_mouseClickItemID = item->data(ItemId).toString();

        if(m_CurrentAction == Action_Eraser)
        {
            QPoint  point=event->pos();
            QPointF pointScene=this->mapToScene(point);
            m_EraserItem->setPos(pointScene.x(),pointScene.y());
            m_EraserItem->setZValue(m_PixmapItem->zValue()+1);
            if(!m_scene->items().contains(m_EraserItem))
                m_scene->addItem(m_EraserItem);
        }
        else if(m_CurrentAction == Action_VirtualWall)
        {
            QPoint  point=event->pos();
            QPointF pointScene=this->mapToScene(point);
            emit sig_MapEditData("VirtualWallStart",QStringList()<<QString::number(pointScene.x()-m_PixmapItem->pos().x())
                                                                   <<QString::number(pointScene.y()-m_PixmapItem->pos().y()));
        }
    }


    QGraphicsView::mousePressEvent(event);
}

void MyGraphicsView::mouseReleaseEvent(QMouseEvent *event)
{
    Q_UNUSED(event)
    m_mouseClickItemID = "";
    QPoint  point=event->pos();
    QPointF pointScene=this->mapToScene(point); //转换到Scene坐标
    QGraphicsItem  *item=NULL;
    item=m_scene->itemAt(pointScene,this->transform()); //获取光标下的绘图项
    // qDebug()<<"Release:"<<item->data(ItemId).toString();
    // qDebug()<<QString::asprintf("View 坐标：%d,%d",point.x(),point.y());
    // qDebug()<<QString::asprintf("Scene 坐标：%.0f,%.0f", pointScene.x(),pointScene.y());

    if (m_CurrentAction == Action_DrawLine) //有绘图项
    {
        if(item != NULL)//绘制线路
        {
            if(item->data(ItemDesciption).toString() == ItemDesciption_Point && is_Line_startItem != NULL)
            {
                is_Line_endItem = item;
                bool is_paitLine = true;
                if(is_Line_endItem == is_Line_startItem)
                    is_paitLine = false;

                foreach(QGraphicsItem  *itemLine,m_scene->items())
                {
                    if(itemLine->data(ItemDesciption).toString() == ItemDesciption_Line)
                    {
                        if(itemLine->data(ItemLineStartItem).toString() == is_Line_startItem->data(ItemId).toString()
                            && itemLine->data(ItemLineEndItem).toString() == is_Line_endItem->data(ItemId).toString())
                        {
                            is_paitLine = false;
                        }
                    }
                }
                if(is_paitLine)
                {
                    QPointF  start;
                    QPointF  end;
                    start.setX(is_Line_startItem->pos().x());
                    start.setY(is_Line_startItem->pos().y());
                    end.setX(is_Line_endItem->pos().x());
                    end.setY(is_Line_endItem->pos().y());

                    TM_PointLineItem *item = new TM_PointLineItem(start,end,is_Line_startItem->data(ItemId).toString(),is_Line_endItem->data(ItemId).toString(),1);
                    item->setPos(is_Line_startItem->pos().x(),is_Line_startItem->pos().y());
                    QString Line_id = QString("%1%2").arg(is_Line_startItem->data(ItemId).toString(),is_Line_endItem->data(ItemId).toString());
                    QByteArray byteArray = Line_id.toUtf8();
                    Line_id = "";
                    for(const char &byte : byteArray) {
                        Line_id += QString::number(static_cast<unsigned char>(byte), 16).toUpper();
                    }

                    item->setData(ItemId,Line_id);
                    item->setData(ItemDesciption,ItemDesciption_Line);
                    item->setData(ItemLineStartItem,is_Line_startItem->data(ItemId).toString());
                    item->setData(ItemLineEndItem,is_Line_endItem->data(ItemId).toString());
                    item->setData(ItemStraightLine,false);
                    item->setSelected(true);
                    QGraphicsEllipseItem   *Ellipse_start=new QGraphicsEllipseItem(-2,-2,4,4);
                    Ellipse_start->setFlags(QGraphicsItem::ItemIsMovable
                                            | QGraphicsItem::ItemIsSelectable
                                            | QGraphicsItem::ItemIsFocusable);
                    Ellipse_start->setFlag(QGraphicsItem::ItemIsMovable,true);
                    Ellipse_start->setBrush(QBrush(Qt::cyan));
                    Ellipse_start->setPen(QPen(Qt::black, 0));
                    Ellipse_start->setZValue(3);
                    Ellipse_start->setPos((start+end)/2);
                    Ellipse_start->setData(ItemId,Line_id+ItemBezier_Strat);
                    Ellipse_start->setData(ItemBezierLineID,Line_id);
                    Ellipse_start->setData(ItemDesciption,ItemBezier_Strat);
                    Ellipse_start->setData(ItemBezierPointID,is_Line_startItem->data(ItemId).toString()
                                                                  +"->"+is_Line_endItem->data(ItemId).toString());

                    QGraphicsEllipseItem   *Ellipse_end=new QGraphicsEllipseItem(-2,-2,4,4);
                    Ellipse_end->setFlags(QGraphicsItem::ItemIsMovable
                                          | QGraphicsItem::ItemIsSelectable
                                          | QGraphicsItem::ItemIsFocusable);
                    Ellipse_end->setFlag(QGraphicsItem::ItemIsMovable,true);
                    Ellipse_end->setBrush(QBrush(Qt::cyan));
                    Ellipse_end->setPen(QPen(Qt::black, 0));
                    Ellipse_end->setZValue(3);
                    Ellipse_end->setPos((start+end)/2);
                    Ellipse_end->setData(ItemId,Line_id+ItemBezier_End);
                    Ellipse_end->setData(ItemBezierLineID,Line_id);
                    Ellipse_end->setData(ItemDesciption,ItemBezier_End);
                    Ellipse_end->setData(ItemBezierPointID,is_Line_startItem->data(ItemId).toString()
                                                                +"->"+is_Line_endItem->data(ItemId).toString());


                    m_scene->addItem(Ellipse_start);
                    m_scene->addItem(Ellipse_end);

                    m_scene->addItem(item);
                    m_scene->clearSelection();

                    on_UpdateLine(is_Line_endItem);
                }
            }
        }
    }
    else if(m_CurrentAction == Action_VirtualWall)
    {
        QPoint  point=event->pos();
        QPointF pointScene=this->mapToScene(point);
        emit sig_MapEditData("VirtualWallEnd_Release",QStringList()<<QString::number(pointScene.x()-m_PixmapItem->pos().x())
                                                               <<QString::number(pointScene.y()-m_PixmapItem->pos().y()));
    }
    else if(m_CurrentAction == Action_mapLocation)
    {
        if(m_RobotItem != NULL && (event->button()== Qt::LeftButton))
        {
            QMessageBox::StandardButton result = QMessageBox::warning(this,tr("Warning消息框"),tr("是否重定位当前位置？"),
                                                                      QMessageBox::Ok|QMessageBox::Cancel,
                                                                      QMessageBox::Ok);

            if(result == QMessageBox::Ok)
            {
                QVariantMap dataMap;
                dataMap["topic"] = g_RobotHandLocalization;
                dataMap["op"] = "publish";

                QVariantMap poseMap;
                QVariantMap positiondata;
                positiondata["x"] = on_X_calibration(true,(m_RobotItem->pos() - m_PixmapItem->pos()).x())*g_map_resolution;
                positiondata["y"] = on_Y_calibration(true,(m_RobotItem->pos() - m_PixmapItem->pos()).y())*g_map_resolution;
                positiondata["z"] = 0;

                qDebug()<<"--------"<<-m_RobotItem->rotation();
                double yaw = -m_RobotItem->rotation()*M_PI/180.0;//偏向角
                double pitch = 0;//俯仰角
                double roll = 0;//翻滚角

                double cy = cos(yaw * 0.5);
                double sy = sin(yaw * 0.5);
                double cp = cos(pitch * 0.5);
                double sp = sin(pitch * 0.5);
                double cr = cos(roll * 0.5);
                double sr = sin(roll * 0.5);

                QVariantMap orientationdata;
                orientationdata["x"] = cy * cp * sr - sy * sp * cr;
                orientationdata["y"] = sy * cp * sr + cy * sp * cr;
                orientationdata["z"] = sy * cp * cr - cy * sp * sr;
                orientationdata["w"] = cy * cp * cr + sy * sp * sr;

                poseMap["position"] = positiondata;
                poseMap["orientation"] = orientationdata;
                QVariantMap pose1Map;
                pose1Map["pose"] = poseMap;

                QVariantMap pose2Map;
                pose2Map["pose"] = pose1Map;

                QVariantMap headerMap;
                headerMap["frame_id"] = "map";
                pose2Map["header"] = headerMap;

                dataMap["msg"] = pose2Map;

                qDebug().noquote() << "TcpSocket::on_SendXYZMove=" << PublicShared::variant2JsonStr(dataMap);
                QJsonDocument jsonDoc = QJsonDocument::fromVariant(dataMap);
                QByteArray byteArray = jsonDoc.toJson(QJsonDocument::Compact);
                emit sig_MapMessage("HandLocalization",QString(byteArray));

            }
        }

        emit sig_MapMessage("action_SelectSetChecked","");
        m_is_ActionIng = false;

    }
    is_Line_startItem = NULL;
    is_Xiugai_Line = false;
    if(m_scene->items().contains(m_EraserItem))
        m_scene->removeItem(m_EraserItem);
    this->viewport()->update();
    QGraphicsView::mouseReleaseEvent(event);
}

void MyGraphicsView::mouseMoveEvent(QMouseEvent *event)
{
    static QPoint lastPoint;
    if(m_CurrentAction == Action_Eraser)
    {
        if(m_scene->items().contains(m_EraserItem) && (lastPoint - event->pos()).manhattanLength() > 5)
        {
            lastPoint = event->pos();
            QPointF pointScene=this->mapToScene(lastPoint);
            m_EraserItem->setPos(pointScene.x(),pointScene.y());
            qDebug()<<"m_EraserItem POS="<<pointScene<<m_EraserItem->pos();
            emit sig_MapEditData("Eraser",QStringList()<<QString::number(pointScene.x()-m_PixmapItem->pos().x()+m_EraserItem->rect().left())
                                                         <<QString::number(pointScene.y()-m_PixmapItem->pos().y()+m_EraserItem->rect().top())
                                                         <<QString::number(m_EraserItem->rect().width())
                                                         <<QString::number(m_EraserItem->rect().height()));
        }
    }
    else if(m_CurrentAction == Action_VirtualWall && (lastPoint - event->pos()).manhattanLength() > 5)
    {
        lastPoint = event->pos();
        QPointF pointScene=this->mapToScene(lastPoint);
        emit sig_MapEditData("VirtualWallEnd",QStringList()<<QString::number(pointScene.x()-m_PixmapItem->pos().x())
                                                               <<QString::number(pointScene.y()-m_PixmapItem->pos().y()));
    }
    else if(m_CurrentAction == Action_mapLocation)
    {
        if(m_RobotItem != NULL)
        {
            QPoint  point=event->pos();
            QPointF pointScene=this->mapToScene(point);
            QPointF pointRobotItem = m_RobotItem->pos();

            double k = double(pointScene.y()-pointRobotItem.y())/double(pointScene.x()-pointRobotItem.x());
            double jiaodu = double(atan(k)) * double(180) / double(3.1415962);
            if(pointScene.y()<pointRobotItem.y() && pointScene.x()<pointRobotItem.x())
            {
                //qDebug()<<"=============1"<<jiaodu-180;
                m_RobotItem->setRotation(jiaodu-180);
            }
            else if(pointScene.y()>pointRobotItem.y() && pointScene.x()<pointRobotItem.x())
            {
                //qDebug()<<"=============2"<<jiaodu+180;
                m_RobotItem->setRotation(jiaodu+180);
            }
            else
            {
                //qDebug()<<"=============3"<<jiaodu;
                m_RobotItem->setRotation(jiaodu);
            }
        }
    }
    else /*if(m_CurrentAction == Action_NULL)*/
    {
        if(m_mouseClickItemID == g_CurrentMapID)
        {
            QPointF point = (event->pos()- m_mousePos)/g_curScaleValue;
            foreach(QGraphicsItem  *item,m_scene->items())
            {
                if(item->data(ItemDesciption).toString() != ItemBezier_Direct)
                {
                    item->moveBy(point.x(), point.y());
                    //qDebug()<<QString::asprintf(" 坐标：%d,%d",point.x(),point.y());
                }
            }
            if(!g_is_OpenMapEdit)
            {
                foreach(QGraphicsEllipseItem  *item,m_bezileItemList)
                {
                    item->moveBy(point.x(), point.y());
                }
            }
        }
        else
        {
            QPoint  point=event->pos();
            QPointF pointScene=this->mapToScene(point); //转换到Scene坐标
            QGraphicsItem  *Pointitem = NULL;
            Pointitem=m_scene->itemAt(pointScene,this->transform()); //获取光标下的绘图项
            if (Pointitem != NULL) //有绘图项
            {
                if((Pointitem->data(ItemDesciption).toString() == ItemDesciption_Point
                     ||Pointitem->data(ItemDesciption).toString() == ItemBezier_Strat
                     ||Pointitem->data(ItemDesciption).toString() == ItemBezier_End) && is_Xiugai_Line && g_is_OpenMapEdit)
                {
                    if(Pointitem->data(ItemDesciption).toString() == ItemDesciption_Point)
                    {
                        slot_LinerAutoSetBazierPos(Pointitem);
                    }
                    on_UpdateLine(Pointitem);//更新路线
                }

                if(Pointitem->data(ItemId).toString()== g_CurrentMapID)
                {
                    QPointF pointXY=Pointitem->mapFromScene(pointScene); //转换为绘图项的局部坐标
                    emit sig_MapMessage("MoucePinot",QString::asprintf("地图坐标-move：%.0f,%.0f", on_X_calibration(true,pointXY.x()),on_Y_calibration(true,pointXY.y())));
                }
            }
        }
    }

    m_mousePos = event->pos();
    this->viewport()->update();
    // qDebug()<<QString::asprintf("View 坐标：%d,%d",event->pos().x(),event->pos().y());
    // QPointF pointScene=this->mapToScene(event->pos()); //转换到Scene坐标
    // qDebug()<<(QString::asprintf("Scene 坐标：%.0f,%.0f", pointScene.x(),pointScene.y()));
    QGraphicsView::mouseMoveEvent(event);
}

void MyGraphicsView::wheelEvent(QWheelEvent *event)
{
    if(m_PixmapItem == nullptr)
        return;
    const double scaleFactor = 1.15;
    if (event->angleDelta().y() > 0) { // 向上滚动放大
        scale(scaleFactor, scaleFactor);
        g_curScaleValue = g_curScaleValue*scaleFactor;

    } else { // 向下滚动缩小
        scale(1.0 / scaleFactor, 1.0 / scaleFactor);
        g_curScaleValue = g_curScaleValue/scaleFactor;
    }
}
